﻿using System;
using System.Collections.Generic;

namespace Orz.Framework.Core.Messaging
{
    /// <summary>
    /// A Messenger call every handlers once-off
    /// </summary>
    public class OnceOffMessenger : GeneralMessenger
    {
        /// <summary>
        /// Does the callback.
        /// </summary>
        /// <param name="actions">The actions.</param>
        /// <param name="isAsyn">if set to <c>true</c> [is asyn].</param>
        /// <param name="args">The args.</param>
        protected override void DoCallback(List<WeakAction> actions, bool isAsyn, params object[] args)
        {
            if (actions != null)
            {
                VoidDelegateHandler handler = new VoidDelegateHandler(() =>
                {
                    while (actions.Count > 0)
                    {
                        WeakAction action = actions[0];
                        Delegate callback = action.CreateAction();
                        if (IsMatchParam(callback, args))
                            callback.DynamicInvoke(args);
                        actions.RemoveAt(0);
                    }
                });

                if (isAsyn)
                {
                    handler.BeginInvoke(null, null);
                }
                else
                {
                    handler.Invoke();
                }
            }
        }
    }
}
